package com.app.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.app.common.Result;
import com.app.mapper.InviteConfigMapper;
import com.app.mapper.InviteRecordMapper;
import com.app.mapper.UserMapper;
import com.app.mapper.VerificationRecordMapper;
import com.app.model.IntegralRecordModel;
import com.app.model.InviteConfigModel;
import com.app.model.InviteRecordModel;
import com.app.model.UserModel;
import com.app.service.IntegralRecordService;
import com.app.service.InviteRecordService;
import com.app.service.UserService;
import com.app.utils.CommonHelp;
import com.app.utils.DateMaskingUtils;
import com.app.utils.StringTool;
import com.app.vo.InviteMonthCountVo;
import com.app.vo.InviteRecordVo;
import com.app.vo.RankingVo;
import com.app.vo.UserVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 邀请记录
 *
 * @author 16693103420
 * @since 2024-02-03
 */
@Service
public class InviteRecordServiceImpl extends ServiceImpl<InviteRecordMapper, InviteRecordModel> implements InviteRecordService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private InviteRecordMapper inviteRecordMapper;
    @Autowired
    private InviteConfigMapper inviteConfigMapper;
    @Autowired
    private VerificationRecordMapper verificationRecordMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private IntegralRecordService integralRecordService;



    @Override
    public IPage<UserModel> getUserInviteRecordList(Integer page, Integer limit,Integer userId){

        Page<UserModel> page1 = new Page<>(page, limit);


        IPage<UserModel> quiltInviteIdList = inviteRecordMapper.quiltInviteUserList(page1,userId);//邀请人列表
        return quiltInviteIdList;
    }


    @Override
    public IPage<UserModel> queryLoginUserInvitationRecord(Integer page, Integer limit, Integer userId,String startTime,String endTime,String name) {
        Page<UserModel> page1 = new Page<>(page, limit);
        IPage<UserModel> list = inviteRecordMapper.queryLoginUserInvitationRecord(page1, userId, startTime,endTime,name);
        return list;
    }


    @Override
    public InviteRecordVo getUserInviteRecord(Integer page, Integer limit, Integer userId, String keyword) {
        String dayDate = CommonHelp.getNowDate();
        String beginTimeDay = dayDate + " 00:00:00";
        String endTimeDay = dayDate + " 23:59:59";
        InviteRecordVo inviteRecordVo = new InviteRecordVo();
        double sumIncomeIntegral = this.verificationRecordMapper.contribution_points_earned_by_individuals(userId);
        Page<InviteRecordModel> page1 = new Page<>(page, limit);
        Page<InviteRecordModel> inviteRecordPage = null;//有可能全部，有可能关键字
        QueryWrapper<InviteRecordModel> qwAll = new QueryWrapper<>();
        qwAll.eq("invite_id", userId);
        Integer selectCount = inviteRecordMapper.selectCount(qwAll);
        QueryWrapper<InviteRecordModel> qw = new QueryWrapper<>();
        qw.eq("invite_id", userId);
        qw.orderByDesc("create_time");
        boolean flag = false;
        if (StringTool.isNotEmpty(keyword)) {
            List<Integer> quiltInviteIdList = inviteRecordMapper.quiltInviteIdList(userId);//邀请人列表
            QueryWrapper<UserModel> userQW = new QueryWrapper<>();
            userQW.like("name", keyword);
            userQW.or().like("phone", keyword);
            if (quiltInviteIdList != null && quiltInviteIdList.size() > 0) {
                userQW.in("id", quiltInviteIdList);
            } else {
                userQW.eq("id", "null");
            }
            List<UserModel> userList = userMapper.selectList(userQW);//符合手机号以及姓名的user列表
            if (CollectionUtil.isNotEmpty(userList)) {
                List<Integer> quiltInviteId = new ArrayList<>();
                for (UserModel userModel : userList) {
                    quiltInviteId.add(userModel.getId());
                }
                qw.in("quilt_invite_id", quiltInviteId);
            } else {
                flag = true;
            }
        }
        //有可能全部有可能带条件的数据
        inviteRecordPage = inviteRecordMapper.selectPage(page1, qw);
        List<InviteRecordModel> inviteRecordList = inviteRecordPage.getRecords();
        //遍历有可能全部有可能带条件的数据
        for (InviteRecordModel inviteRecord : inviteRecordList) {
            Integer quiltInviteId = inviteRecord.getQuiltInviteId();//被邀请人用户ID
            UserModel quiltInviteUser = userMapper.selectById(quiltInviteId);
            inviteRecord.setUserName(quiltInviteUser.getName());
            inviteRecord.setFaceUrl(quiltInviteUser.getFaceUrl());
            inviteRecord.setInvitationCode(quiltInviteUser.getInvitationCode());
            inviteRecord.setVip(quiltInviteUser.getVip());
            String phone = quiltInviteUser.getPhone();
            String mobilePhone = DateMaskingUtils.mobilePhone(phone);
            inviteRecord.setPhone(mobilePhone);
            Double todayConsume = Math.abs(verificationRecordMapper.userTodayConsume(beginTimeDay, endTimeDay, quiltInviteId));
            if (todayConsume == null) {
                todayConsume = 0.0;
            }
            inviteRecord.setTodayConsume(todayConsume);//被邀请人今日消费
            Double sumConsume = Math.abs(verificationRecordMapper.userSumConsume(quiltInviteId));
            if (sumConsume == null) {
                sumConsume = 0.0;
            }
            inviteRecord.setSumConsume(sumConsume);//被邀请人累计消费
            InviteConfigModel inviteConfigModel = inviteConfigMapper.selectById(1);
            Double consumptionRatio = inviteConfigModel.getBrokerageTwo();
            Double todayIncome = todayConsume * consumptionRatio;
            inviteRecord.setTodayIncome(todayIncome);//被邀请人给自己带来的今日收益

//            Double contributeIntegral = verificationRecordMapper.sumContributeIntegral(quiltInviteId);
//            if (contributeIntegral == null) {
//                contributeIntegral = 0.0;
//            }
//            inviteRecord.setContributeIntegral(contributeIntegral);//被邀请人累计贡献积分
//            sumIncomeIntegral = sumIncomeIntegral + contributeIntegral;
        }
        if (flag){
            inviteRecordVo.setList(new ArrayList<>());
        }else {
            inviteRecordVo.setList(inviteRecordList);
        }
        inviteRecordVo.setCount((int) inviteRecordPage.getTotal());
        inviteRecordVo.setFansCount(selectCount);
        inviteRecordVo.setSumIncomeIntegral(sumIncomeIntegral);//获得积分累计
        return inviteRecordVo;

    }

    //邀请好友
//    @Override
//    public void inviteUser(String invitationCode, Integer quiltInviteId) {
//        UserModel inviteUser = userService.getUserByInviteCode(invitationCode);
//        if (inviteUser != null) {
//            InviteRecordModel inviteRecordModel = inviteRecordMapper.firstInviteRecord(inviteUser.getId());
//            InviteConfigModel inviteConfig = inviteConfigMapper.selectById(1);
//            if (number.equals(inviteConfig.getInviteCount())) {
//                number = 0;
//                inviteUser.setIntegral(inviteUser.getIntegral() + inviteConfig.getInviteVoucher());
//                userMapper.updateById(inviteUser);
//                //新增积分记录
//                IntegralRecordModel integralRecordModel = new IntegralRecordModel();
//                integralRecordModel.setName("邀请好友获得积分");
//                integralRecordModel.setTypeName("邀请好友");
//                String amountIntegral = "+" + inviteConfig.getInviteVoucher() + "分";
//                integralRecordModel.setIntegral(amountIntegral);
//                integralRecordModel.setUserId(inviteUser.getId());
//                integralRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
//                integralRecordModel.setVoucherType(1);
//                integralRecordModel.setVoucherAmount(Double.valueOf(inviteConfig.getInviteVoucher()));
//                integralRecordService.save(integralRecordModel);
//            }
//            if (inviteRecordModel == null) {
//                inviteRecordModel = new InviteRecordModel();
//            }
//            inviteRecordModel.setInviteId(inviteUser.getId());
//            inviteRecordModel.setQuiltInviteId(quiltInviteId);
//            inviteRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
//            inviteRecordModel.setNumber(number);
//            inviteRecordMapper.insert(inviteRecordModel);
//        }
//    }

    //查询本月邀请人数
    @Override
    public InviteMonthCountVo inviteUserMonthCount(Integer userId) {
        String dayDate = CommonHelp.getNowDate();
        String monthDate = dayDate.substring(0, 7);

        String beginTimeMonth = monthDate + "-01 00:00:00";
        String endTimeDay = dayDate + " 23:59:59";
        InviteMonthCountVo vo = new InviteMonthCountVo();
        InviteConfigModel inviteConfigModel = inviteConfigMapper.selectById(1);
        Integer inviteCount = inviteConfigModel.getInviteCount();

        InviteRecordModel inviteRecordModel = inviteRecordMapper.firstMonthInviteRecord(beginTimeMonth, endTimeDay, userId);
        if (inviteRecordModel != null) {
            Integer number = inviteRecordModel.getNumber();
            if (number == null) {
                number = 0;
            }
            vo.setCount(number);
        }
        vo.setMaxCount(inviteCount);
        return vo;
    }


}
